//
//  JWFindBussinessReleaseVC.m
//  jinwang
//
//  Created by jzb on 2018/4/12.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "JWFindBussinessReleaseVC.h"
#import "JWFBFacadeVCModel.h"
#import "JWFindBussinessReleaseExitVC.h"

@interface JWFindBussinessReleaseVC ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    
    TYAlertController *_alertController;
}
@property (weak, nonatomic) IBOutlet UILabel *TypeLabel;

@property (weak, nonatomic) IBOutlet UITextField *TitleTF;

@property (weak, nonatomic) IBOutlet UILabel *ValueLabel;

@property (nonatomic,strong) NSMutableArray *list;

@property (nonatomic,strong)NSMutableArray *imageMarkArray;//图片对应的记号`0`表示第0张图片
@property (nonatomic,strong)NSMutableArray *imageUploadedNameArray;//所有上传图片名字数组（上传图片之后，返回的名字）
@property (nonatomic,strong)NSMutableArray *imageUploadedArray;//图片数组
@property (nonatomic,strong)NSMutableArray *imageDownloadedNameArray;//之前上传的oldHtmlString解析出来的图片地址

@property (nonatomic,assign) BOOL hasEndDiv;
@property (nonatomic,assign) BOOL hasHeadDiv;
@property (nonatomic,assign) NSInteger imageIndex;

@property (strong, nonatomic) UIView *pickerBGView;
@property (strong, nonatomic) UIPickerView *pickerView;
@property (strong, nonatomic) JWFBFacadeVCModel *selectModel;

@property (strong, nonatomic) NSAttributedString *AttributedString;
@property (nonatomic,strong) NSMutableString *resultString;//拼接之后的字符串

@end

@implementation JWFindBussinessReleaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发布";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.f) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    _AttributedString = [NSAttributedString new];
    _resultString = [[NSMutableString alloc] init];
    _imageMarkArray = [[NSMutableArray alloc] init];
    _imageUploadedArray = [[NSMutableArray alloc] init];
    _imageUploadedNameArray = [[NSMutableArray alloc] init];
    _imageDownloadedNameArray = [[NSMutableArray alloc] init];
    [self makeUrl_Business_allTag];
    [self pickerViewBuild];
}
- (void)pickerViewBuild{
    
    _pickerBGView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 250)];
    _pickerBGView.backgroundColor = kRGBColor(240, 240, 240);
    UIButton *quxiaoBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 50)];
    quxiaoBtn.tag = 1000;
    [quxiaoBtn setTitle:@"取消" forState:UIControlStateNormal];
    [quxiaoBtn addTarget:self action:@selector(pickerBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [quxiaoBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_pickerBGView addSubview:quxiaoBtn];
    
    UIButton *quedingBtn = [[UIButton alloc]initWithFrame:CGRectMake(_pickerBGView.width - 80, 0, 80, 50)];
    [quedingBtn setTitle:@"确定" forState:UIControlStateNormal];
    quedingBtn.tag = 1001;
    [quedingBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [quedingBtn addTarget:self action:@selector(pickerBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickerBGView addSubview:quedingBtn];
    
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, quxiaoBtn.height, kScreenWidth, _pickerBGView.height - quxiaoBtn.height)];
    
    self.pickerView.backgroundColor = [UIColor whiteColor];
    
    self.pickerView.delegate = self;
    
    self.pickerView.dataSource = self;
    
    [_pickerBGView addSubview:self.pickerView];
    
//    [self.pickerView reloadAllComponents];//刷新UIPickerView
    

}
- (IBAction)TypeBtn:(UIButton *)sender {
    
    _alertController = [TYAlertController alertControllerWithAlertView:_pickerBGView preferredStyle:TYAlertControllerStyleActionSheet];
    _alertController.backgoundTapDismissEnable = YES;
    [self presentViewController:_alertController animated:YES completion:nil];
}
- (void)pickerBtnOnclick:(UIButton *)sender{
    
    [_alertController dismissViewControllerAnimated:NO];
    if (sender.tag == 1000) {
        
    }else if (sender.tag == 1001){
        
        self.TypeLabel.text = _selectModel.tag_name;
    }
    
}
- (IBAction)ValueBtn:(UIButton *)sender {
    
    JWFindBussinessReleaseExitVC *VC = [JWFindBussinessReleaseExitVC new];
    
    VC.ExitBlcok = ^(NSAttributedString *AttributedString) {
      
        NSLog(@"0-0--=-=-=-=>>>%@",AttributedString);
        if (AttributedString.length > 0) {
            _AttributedString = AttributedString;
            self.ValueLabel.hidden = NO;
        }
    };
    
    if (_AttributedString.length > 0) {
        
        VC.ExitAttributedString = _AttributedString;
    }
    
    [self.navigationController pushViewController:VC animated:YES];
}


- (IBAction)LiJiFaBuBut:(UIButton *)sender {
    
    if (_AttributedString.length > 0) {
        
        _hasEndDiv = false;
        _hasHeadDiv = false;
        _imageIndex = 0;
        
        NSAttributedString * att = _AttributedString;
        NSMutableAttributedString * resultAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];
        //    __weak __block UITextView * copy_self = self; //枚举出所有的附件字符串
        [att enumerateAttributesInRange:NSMakeRange(0, att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
            NSTextAttachment * textAtt = attrs[@"NSAttachment"];//从字典中取得那一个图片
            if (textAtt) {
                if (self.hasEndDiv == true) {
                    self.hasHeadDiv = true;
                    self.hasEndDiv = false;
                }
                
                UIImage * image = textAtt.image;
                [_resultString insertString:[NSString stringWithFormat:@"`%ld`",self.imageIndex] atIndex:0];
                [self.imageMarkArray addObject:[NSString stringWithFormat:@"`%ld`",self.imageIndex]];
                [self.imageUploadedArray addObject:image];
                self.imageIndex ++;
            } else {
                if (self.hasEndDiv == false) {
                    self.hasEndDiv = true;
                }
                [_resultString insertString:[resultAtt attributedSubstringFromRange:range].string atIndex:0];
            }
        }];
        
        NSLog(@"%@",_resultString);
        //上传图片，拼接字符串
        if (self.imageUploadedArray.count > 0) {
            [self uploadImageArray];
        }
    }
    
}
- (void)uploadImageArray {
    _imageIndex = 0;//用来计数
    [MBProgressHUD showHUDAddedTo:self.view animated:true];
    for (int i = 0; i < _imageUploadedArray.count; i ++) {
        [self uploadHeadImage:_imageUploadedArray[i] imageIndex:i];
    }
}
- (void)uploadHeadImage:(UIImage *)image imageIndex:(NSInteger)index{
    
    //将图片上传到服务器
    [NSThread sleepForTimeInterval:0.5];
    [UploadImageTool uploadImage:image progress:^(NSString *key, float percent) {
        
    } success:^(NSString *url) {
        
        [_imageUploadedNameArray addObject:url];
        
        NSArray *array = [self.resultString componentsSeparatedByString:self.imageMarkArray[index]];
        
        if (array.count == 1) {
            if (index != 0) {//说明是最前面的一个image
                self.resultString = [NSMutableString stringWithFormat:@"<br><img src=\"%@\"><br>%@",url,array[0]];
            } else {//说明是最后面的一个image
                self.resultString = [NSMutableString stringWithFormat:@"%@<br><img src=\"%@\"><br>",array[0],url];
            }
        } else {
            self.resultString = [NSMutableString stringWithFormat:@"%@<br><img src=\"%@\"><br>%@",array[0],url,array[1]];
        }
        _imageIndex ++;
        if (_imageIndex == _imageUploadedArray.count) {//图片都上传完了
            
            [self makeUrl_Business_addBusiness];

            //删除在编辑中删掉的图片
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for (int i = 0; i < _imageDownloadedNameArray.count; i ++) {
                for (int j = 0; j < _imageUploadedNameArray.count; j ++) {
                    if ([_imageDownloadedNameArray[i] isEqualToString:_imageUploadedNameArray[j]]) {
                        continue;
                    }
                }
                [tempArray addObject:_imageDownloadedNameArray[i]];
            }
        }
        
    } failure:^{
        
    }];
}

#pragma mark pickerview function
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [_list count];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    
    return 36.0f;
    
}
- (CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{

    return  kScreenWidth;
}

// 自定义指定列的每行的视图，即指定列的每行的视图行为一致

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    if (!view){
        
        view = [[UIView alloc]init];
        
    }
    
    UILabel *text = [[UILabel alloc]initWithFrame:CGRectMake(0, 8, kScreenWidth, 20)];
    
    text.textAlignment = NSTextAlignmentCenter;
    
    JWFBFacadeVCModel *model = _list[row];
    text.text = model.tag_name;
    
    [view addSubview:text];
    
    //隐藏上下直线
    
    [self.pickerView.subviews objectAtIndex:1].backgroundColor = UIColorHex(0xEEA72B);
    
    [self.pickerView.subviews objectAtIndex:2].backgroundColor = UIColorHex(0xEEA72B);
    
    return view;
    
}
//显示的标题

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    JWFBFacadeVCModel *model = _list[row];
    
    return model.tag_name;
    
}
//显示的标题字体、颜色等属性

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    JWFBFacadeVCModel *model = _list[row];
    
    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc]initWithString:model.tag_name];
    
    [AttributedString addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18], NSForegroundColorAttributeName:UIColorHex(0xEEA72B)} range:NSMakeRange(0, [AttributedString  length])];
    
    return AttributedString;
    
}//NS_AVAILABLE_IOS(6_0);

//被选择的行
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
//    NSLog(@"HANG%@",[_nameArray objectAtIndex:row]);
     JWFBFacadeVCModel *model = _list[row];
    _selectModel = model;
    
}
//快急商务获取更多标签
-(void)makeUrl_Business_allTag{
    [[DDNetworkManagerDate makeUrl_Business_allTagWithtoken:k_user_token] post_RequestFinshSuccess:^(id responseObject) {
        if ([self requestFinshCode:responseObject isShowMessage:NO] == 1) {
            _list = [NSMutableArray new];
            NSArray *data = [responseObject objectForKey:kRequsetDataKey];
            //转模型
            NSMutableArray *arr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                JWFBFacadeVCModel *model = [JWFBFacadeVCModel yy_modelWithDictionary:obj];
                [arr addObject:model];
            }];
            self.list = arr.mutableCopy;
            if (_list.count > 0) {
                
                _selectModel = self.list[0];
            }
            
        }
        [self.pickerView reloadAllComponents];
    } failure:^(id errorObject) {
        
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//发布快急商务
-(void)makeUrl_Business_addBusiness{
    [[DDNetworkManagerDate makeUrl_Business_addBusinessWithtoken:k_user_token tag_id1:[_selectModel.tag_id stringValue] tag_id2:@"" business_title:_TitleTF.text business_content:self.resultString day:@"1"] post_RequestFinshSuccess:^(id responseObject) {
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            [self goBack];
        }
    } failure:^(id errorObject) {
        
        [self showBottomMessag:@"网络请求失败"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
